package com.cxh.rmsq.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.cxh.rmsq.R;
import com.cxh.rmsq.common.Constant;
import com.cxh.rmsq.common.IntentExtra;
import com.cxh.rmsq.common.ThreadManager;
import com.cxh.rmsq.db.DBManager;
import com.cxh.rmsq.db.dao.UserDao;
import com.cxh.rmsq.db.model.AuthenticationBean;
import com.cxh.rmsq.db.model.MineBean;
import com.cxh.rmsq.db.model.UserInfo;
import com.cxh.rmsq.im.IMManager;
import com.cxh.rmsq.model.Resource;
import com.cxh.rmsq.model.Resource2;
import com.cxh.rmsq.model.Status;
import com.cxh.rmsq.model.VersionInfo;
import com.cxh.rmsq.model.qrcode.QrCodeDisplayType;
import com.cxh.rmsq.net.newNet.BaseResultEntity;
import com.cxh.rmsq.net.newNet.ProjectViewModel;
import com.cxh.rmsq.net.newNet.TreasureViewModel;
import com.cxh.rmsq.ui.activity.AboutSealTalkActivity;
import com.cxh.rmsq.ui.activity.AccountSettingActivity;
import com.cxh.rmsq.ui.activity.AddFriendActivity;
import com.cxh.rmsq.ui.activity.ChangeLanguageActivity;
import com.cxh.rmsq.ui.activity.MainActivity;
import com.cxh.rmsq.ui.activity.ProxySettingActivity;
import com.cxh.rmsq.ui.activity.QrCodeDisplayActivity;
import com.cxh.rmsq.ui.activity.ScanActivity;
import com.cxh.rmsq.ui.activity.TranslationSettingActivity;
import com.cxh.rmsq.ui.activity.self.FansActivity;
import com.cxh.rmsq.ui.activity.self.InviteListActivity;
import com.cxh.rmsq.ui.activity.self.LoginPcActivity;
import com.cxh.rmsq.ui.activity.self.LookMeActivity;
import com.cxh.rmsq.ui.activity.self.LookUserDetailActivity2;
import com.cxh.rmsq.ui.activity.self.MineTrendsListActivity;
import com.cxh.rmsq.ui.activity.self.MyBillListActivity;
import com.cxh.rmsq.ui.activity.self.OrderListActivity;
import com.cxh.rmsq.ui.activity.self.SettingActivity;
import com.cxh.rmsq.ui.activity.self.TestActivity;
import com.cxh.rmsq.ui.activity.self.VIPOpenActivity;
import com.cxh.rmsq.ui.adapter.TagAdapter;
import com.cxh.rmsq.ui.view.SettingItemView;
import com.cxh.rmsq.ui.view.UserInfoItemView;
import com.cxh.rmsq.ui.widget.SelectableRoundedImageView;
import com.cxh.rmsq.utils.CharacterParser;
import com.cxh.rmsq.utils.CustomPermissionUtil;
import com.cxh.rmsq.utils.RegexUtils;
import com.cxh.rmsq.utils.RongGenerate;
import com.cxh.rmsq.utils.log.SLog;
import com.cxh.rmsq.utils.permission.AppPermissionUtil;
import com.cxh.rmsq.viewmodel.AppViewModel;
import com.cxh.rmsq.viewmodel.UserInfoViewModel;

import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.hjq.shape.drawable.ShapeGradientOrientation;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.layout.ShapeRelativeLayout;
import com.hjq.shape.view.ShapeTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.UserDataProvider;
import io.rong.imkit.userinfo.model.GroupUserInfo;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.utils.language.LangUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.cs.model.CSCustomServiceInfo;
import io.rong.imlib.model.ConversationIdentifier;
import io.rong.imlib.model.Group;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class MainMeFragment extends BaseFragment {

    private static final String TAG = "MainMeFragment";

    private SettingItemView sivAbout;
    private UserInfoItemView uivUserInfo;
    private AppViewModel appViewModel;
    private SettingItemView sivLanguage;
    private UserInfoViewModel userInfoViewModel;
    private SelectableRoundedImageView iv_left_header;
    private RecyclerView tvIp;
    private TextView tv_name, tv_sex_age, tv_id_number, tv_focus, tv_fan, tv_zan, tv_mine_trend, tv_mine_lookme, tv_mine_melook, tv_vip_money;
    private String avatar = "";
    private ShapeRelativeLayout srlGoVip;
    private ImageView sllVip, iv_scan;
    private ShapeTextView stv_right_open;
    private ImageView ivVipFlag;
    private TextView tv_vip_data;

    @Override
    protected int getLayoutResId() {
        return R.layout.main_fragment_me;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

//        findView(R.id.cl_toolbar).setPadding(0, 0, 0, 0);
////        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
//        BarUtils.setStatusBarColor(getActivity(), ColorUtils.getColor(R.color.transparent));
//        BarUtils.setStatusBarLightMode(getActivity(), true);
    }

    @Override
    protected void onInitView(Bundle savedInstanceState, Intent intent) {

        tv_name = findView(R.id.tv_name);
        tv_sex_age = findView(R.id.tv_sex_age);
        tvIp = findView(R.id.tv_ip);
        tv_id_number = findView(R.id.tv_id_number);
        tv_focus = findView(R.id.tv_focus);
        tv_fan = findView(R.id.tv_fan);
        tv_zan = findView(R.id.tv_zan);
        tv_mine_trend = findView(R.id.tv_mine_trend);
        tv_mine_lookme = findView(R.id.tv_mine_lookme);
        tv_mine_melook = findView(R.id.tv_mine_melook);
        iv_left_header = findView(R.id.iv_left_header, true);

        tv_vip_money = findView(R.id.tv_vip_money);
        sllVip = findView(R.id.sll_vip);
        ivVipFlag = findView(R.id.iv_vip_flag);
        tv_vip_data = findView(R.id.tv_vip_data);
        stv_right_open = findView(R.id.stv_right_open);

        uivUserInfo = findView(R.id.uiv_userinfo, true);
        findView(R.id.siv_setting_qrcode, true);
        findView(R.id.cl_edit_user_info, true);
        findView(R.id.tv_mine_code, true);
        findView(R.id.tv_mine_invite, true);
        findView(R.id.siv_setting_account, true);
        sivLanguage = findView(R.id.siv_language, true);
        findView(R.id.siv_feedback, true);
        sivAbout = findView(R.id.siv_about, true);
        findView(R.id.siv_translation, true);
        findView(R.id.siv_proxy_setting, true);
        findView(R.id.tv_mine_set, true);
        findView(R.id.tv_mine_kefu, true);
        findView(R.id.tv_mine_order, true);
        findView(R.id.tv_mine_bill, true);
        srlGoVip = findView(R.id.srl_go_vip, true);
        iv_scan = findView(R.id.iv_scan, true);

        findView(R.id.ll_mine_trend, true);
        findView(R.id.ll_mine_lookme, true);
        findView(R.id.ll_mine_melook, true);

        findView(R.id.ll_focus, true);
        findView(R.id.ll_fan, true);
        findView(R.id.ll_zan, true);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(IMManager.getInstance().getCurrentId())) {
            io.rong.imlib.model.UserInfo userInfo =
                    RongUserInfoManager.getInstance()
                            .getUserInfo(IMManager.getInstance().getCurrentId());
//            if (userInfo == null) {
            userInfoViewModel.requestUserInfo(IMManager.getInstance().getCurrentId());
            userInfoViewModel.requestUserSelfInfo(IMManager.getInstance().getCurrentId());
//            }
        }
        userInfoViewModel
                .getUserSelfInfo()
                .observe(
                        getActivity(),
                        new Observer<Resource2<MineBean>>() {
                            @Override
                            public void onChanged(Resource2<MineBean> resource) {
                                if (resource.data != null) {
                                    MineBean info = resource.data;
                                    if (resource.status == Status.SUCCESS
                                            || resource.status == Status.ERROR) {
                                        uivUserInfo.setName(info.getNickname());
                                        tv_name.setText(info.getNickname());
                                        tv_sex_age.setText(info.getAge() + "");
                                        tv_focus.setText(info.getGzCount() + "");
                                        tv_fan.setText(info.getFollowerCount() + "");
                                        tv_zan.setText(info.getLikedCount() + "");
                                        tv_mine_trend.setText(info.getContentCount() + "");
                                        tv_mine_lookme.setText(info.getSkwCount() + "");
                                        tv_mine_melook.setText(info.getWksCount() + "");
//                                        tv_id_number.setText(RegexUtils.hideMobile(info.getMobile()));
                                        tv_id_number.setText("ID：" + info.getUserNum());

                                        if (!TextUtils.isEmpty(info.getAvatar())) {
                                            avatar = info.getAvatar();
                                            Glide.with(getActivity())
                                                    .load(info.getAvatar())
                                                    .placeholder(R.drawable.rc_default_portrait)
                                                    .into(iv_left_header);
                                        } else {
                                            avatar = RongGenerate.generateDefaultAvatar(
                                                    getContext(), info.getId() + "", info.getNickname());
                                            Glide.with(getActivity())
                                                    .load(avatar)
                                                    .placeholder(R.drawable.rc_default_portrait)
                                                    .into(iv_left_header);
                                        }

                                        if (1 == info.getSex()) {
                                            tv_sex_age.setCompoundDrawablesWithIntrinsicBounds(
                                                    getActivity().getResources().getDrawable(R.mipmap.icon_male),
                                                    null,
                                                    null,
                                                    null
                                            );
                                            tv_sex_age.setBackgroundResource(R.drawable.shape_sex_male_bg);
                                        } else {
                                            tv_sex_age.setCompoundDrawablesWithIntrinsicBounds(
                                                    requireContext().getResources().getDrawable(R.mipmap.icon_male),
                                                    null,
                                                    null,
                                                    null
                                            );
                                            tv_sex_age.setBackgroundResource(R.drawable.shape_sex_female_bg);
                                        }

                                        SPUtils.getInstance().put("vipLevel", info.getVipLevel());
                                        if (info.getVipLevel() == 0) {//没开会员
                                            sllVip.setVisibility(View.GONE);
                                            tv_vip_data.setVisibility(View.GONE);
                                            tv_vip_money.setText("");
                                            tv_vip_money.setVisibility(View.VISIBLE);
                                            stv_right_open.setVisibility(View.VISIBLE);
                                            ivVipFlag.setImageResource(R.mipmap.icon_mine_vip_flag_qian);
                                            srlGoVip.getShapeDrawableBuilder().setSolidColor(Color.parseColor("#FCF6E7")).intoBackground();
                                        } else {
                                            sllVip.setVisibility(View.VISIBLE);
                                            tv_vip_data.setVisibility(View.VISIBLE);
                                            tv_vip_data.setText(TimeUtils.millis2String(info.getVipExpirationTime(), "yyyy-MM-dd"));
                                            tv_vip_money.setVisibility(View.GONE);
                                            stv_right_open.setVisibility(View.GONE);
                                            ivVipFlag.setImageResource(R.mipmap.icon_mine_vip_flag_shen);
                                            srlGoVip.getShapeDrawableBuilder().setSolidGradientColors(Color.parseColor("#FDF4DA"), Color.parseColor("#FED77A"))
                                                    .setSolidGradientOrientation(ShapeGradientOrientation.BOTTOM_LEFT_TO_TOP_RIGHT).intoBackground();

                                        }
                                        ArrayList<String> list = new ArrayList<>();
                                        if (!TextUtils.isEmpty(info.getLoginIpLoacationName())) {
                                            list.add("IP:" + info.getLoginIpLoacationName());
                                        }
                                        if (!TextUtils.isEmpty(info.getConstellation())) {
                                            list.add(info.getConstellation());
                                        }
                                        if (!TextUtils.isEmpty(info.getMbti())) {
                                            list.add(info.getMbti());
                                        }
                                        tvIp.setLayoutManager(new FlexboxLayoutManager(getActivity()));
//                                    tvIp.setAdapter();  TagAdapter(list, list.size > 3)
                                        TagAdapter tagAdapter = new TagAdapter(list, list.size() > 3);
                                        tvIp.setAdapter(tagAdapter);

//                                        new Handler().post(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                saveAndSyncUserInfo(info.getId() + "", info.getNickname(), avatar);
//                                            }
//                                        });
//
                                        IMManager.getInstance()
                                                .updateUserInfoCache(
                                                        info.getId() + "",
                                                        info.getNickname(),
                                                        Uri.parse(avatar),
                                                        "");
                                        io.rong.imlib.model.UserInfo userInfo = new io.rong.imlib.model.UserInfo(info.getId() + "",
                                                info.getNickname(), Uri.parse(avatar));
                                        RongIM.getInstance().setCurrentUserInfo(userInfo);
                                        RongIM.setUserInfoProvider(new UserDataProvider.UserInfoProvider() {
                                            @Override
                                            public io.rong.imlib.model.UserInfo getUserInfo(String userId) {
                                                return userInfo;
                                            }
                                        }, true);
                                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                                    }

                                }
                            }
                        });

//        userInfoViewModel
//                .getUserInfo()
//                .observe(
//                        getActivity(),
//                        new Observer<Resource<UserInfo>>() {
//                            @Override
//                            public void onChanged(Resource<UserInfo> resource) {
//                                if (resource.data != null) {
//                                    UserInfo info = resource.data;
//
//                                    if (resource.status == Status.SUCCESS
//                                            || resource.status == Status.ERROR) {
//                                        if (!TextUtils.isEmpty(info.getPortraitUri())
//                                                && getActivity() != null) {
//                                            Glide.with(getActivity())
//                                                    .load(info.getPortraitUri())
//                                                    .placeholder(R.drawable.rc_default_portrait)
//                                                    .into(uivUserInfo.getHeaderImageView());
//                                        }
//                                    }
//                                }
//                            }
//                        });
    }

    @Override
    protected void onInitViewModel() {
        appViewModel = ViewModelProviders.of(getActivity()).get(AppViewModel.class);
        RongUserInfoManager.getInstance().addUserDataObserver(mUserDataObserver);

        userInfoViewModel = ViewModelProviders.of(this).get(UserInfoViewModel.class);

//        appViewModel
//                .getHasNewVersion()
//                .observe(
//                        this,
//                        new Observer<Resource<VersionInfo.AndroidVersion>>() {
//                            @Override
//                            public void onChanged(Resource<VersionInfo.AndroidVersion> resource) {
//                                if (resource.status == Status.SUCCESS && resource.data != null) {
//                                    sivAbout.setTagImageVisibility(View.VISIBLE);
//                                }
//                            }
//                        });

        appViewModel
                .getLanguageLocal()
                .observe(
                        this,
                        new Observer<LangUtils.RCLocale>() {
                            @Override
                            public void onChanged(LangUtils.RCLocale rcLocale) {
                                if (rcLocale == LangUtils.RCLocale.LOCALE_US) {
                                    sivLanguage.setValue(R.string.lang_english);
                                } else if (rcLocale == LangUtils.RCLocale.LOCALE_CHINA) {
                                    sivLanguage.setValue(R.string.lang_chs);
                                } else if (rcLocale == LangUtils.RCLocale.LOCALE_ARAB) {
                                    sivLanguage.setValue(R.string.lang_arab);
                                }
                            }
                        });
    }

    @Override
    protected void onClick(View v, int id) {
        switch (id) {
            case R.id.siv_setting_qrcode:
            case R.id.tv_mine_code:
                Intent qrCodeIntent = new Intent(getActivity(), QrCodeDisplayActivity.class);
                qrCodeIntent.putExtra(
                        IntentExtra.STR_TARGET_ID, RongIM.getInstance().getCurrentUserId());
                qrCodeIntent.putExtra(
                        IntentExtra.SERIA_QRCODE_DISPLAY_TYPE, QrCodeDisplayType.PRIVATE);
                startActivity(qrCodeIntent);
                break;
            case R.id.cl_edit_user_info:
            case R.id.uiv_userinfo:
//                Intent intentUserInfo = new Intent(getActivity(), MyAccountActivity.class);
//                Intent intentUserInfo = new Intent(getActivity(), EditUserInfoActivity.class);
//                startActivity(intentUserInfo);
                Intent intentUserInfo = new Intent(getContext(), LookUserDetailActivity2.class);
                intentUserInfo.putExtra(IntentExtra.STR_TARGET_ID, RongIM.getInstance().getCurrentUserId());
                intentUserInfo.putExtra("isContact", "1");
                startActivity(intentUserInfo);
                break;
            case R.id.siv_setting_account:
                startActivity(new Intent(getActivity(), AccountSettingActivity.class));
                break;
            case R.id.tv_mine_set:
                startActivity(new Intent(getActivity(), SettingActivity.class));
//                startActivity(new Intent(getActivity(), AccountSettingActivity.class));
                break;
            case R.id.tv_mine_kefu:
                RongIM.getInstance().startPrivateChat(getActivity(), "1", "人脉社区客服");
                break;
            case R.id.tv_mine_order:
                startActivity(new Intent(getActivity(), OrderListActivity.class));
                break;
            case R.id.tv_mine_bill:
                //我的账单
                startActivity(new Intent(getActivity(), MyBillListActivity.class));
                break;
            case R.id.srl_go_vip:
                //开通VIP
                startActivity(new Intent(getActivity(), VIPOpenActivity.class)
                        /*.putExtra("nickName", tv_name.getText().toString().trim())
                        .putExtra("avatar", avatar)*/);
                break;
            case R.id.tv_mine_invite:
                startActivity(new Intent(getActivity(), InviteListActivity.class));
//                startActivity(new Intent(getActivity(), TestActivity.class));
                break;
            case R.id.siv_language:
                startActivity(new Intent(getActivity(), ChangeLanguageActivity.class));
                break;
            case R.id.siv_feedback:
                CSCustomServiceInfo.Builder builder = new CSCustomServiceInfo.Builder();
                builder.province(getString(R.string.beijing));
                builder.city(getString(R.string.beijing));
                io.rong.imlib.model.UserInfo info =
                        RongUserInfoManager.getInstance()
                                .getUserInfo(RongIM.getInstance().getCurrentUserId());
                if (info != null && !TextUtils.isEmpty(info.getName())) {
                    builder.name(info.getName());
                }
                // 佳信客服配置
                builder.referrer("10001");
                Bundle bundle = new Bundle();
                bundle.putString(
                        RouteUtils.TITLE, getString(R.string.seal_main_mine_online_custom_service));
                bundle.putParcelable(RouteUtils.CUSTOM_SERVICE_INFO, builder.build());
                RouteUtils.routeToConversationActivity(
                        getContext(), ConversationIdentifier.obtainCustomer("service"), bundle);
                break;
            case R.id.siv_about:
                Intent intent = new Intent(getActivity(), AboutSealTalkActivity.class);
                Resource<VersionInfo.AndroidVersion> resource =
                        appViewModel.getHasNewVersion().getValue();
                if (resource != null
                        && resource.data != null
                        && !TextUtils.isEmpty(resource.data.getUrl())) {
                    intent.putExtra(IntentExtra.URL, resource.data.getUrl());
                }
                startActivity(intent);
                break;
            case R.id.siv_translation:
                intent = new Intent(getActivity(), TranslationSettingActivity.class);
                startActivity(intent);
                break;
            case R.id.siv_proxy_setting:
                intent = new Intent(getActivity(), ProxySettingActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_mine_trend:
                startActivity(new Intent(getActivity(), MineTrendsListActivity.class)//我的动态
                        .putExtra("isLookMe", true));
                break;
            case R.id.ll_mine_lookme:
                startActivity(new Intent(getActivity(), LookMeActivity.class)//看过我
                        .putExtra("isLookMe", 1));
                break;
            case R.id.ll_mine_melook:
                startActivity(new Intent(getActivity(), LookMeActivity.class)//wokanguo
                        .putExtra("isLookMe", 2));
                break;
            case R.id.ll_focus:
                startActivity(new Intent(getActivity(), FansActivity.class)
                        .putExtra("isFans", false));
                break;
            case R.id.ll_fan:
                startActivity(new Intent(getActivity(), FansActivity.class)
                        .putExtra("isFans", true));
                break;
            case R.id.ll_zan:
                startActivity(new Intent(getActivity(), LookMeActivity.class)//
                        .putExtra("isLookMe", 3));
                break;
            case R.id.iv_scan:
                toScanQRCode();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100: //qrCode
                    String qrCode = data.getStringExtra("qrCode").split("=")[1];
                    SLog.i("qrCode", qrCode);
                    getActivity().startActivity(new Intent(getActivity(), LoginPcActivity.class)
                            .putExtra("qrCode", qrCode));

            }
        }
    }

    /**
     * 扫一扫
     */
    private void toScanQRCode() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//            // 显示对话框告知用户权限使用目的
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("权限申请")
                    .setMessage("为了便于您使用扫码功能，我们需要访问您的相机权限。")
                    .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Dialog permissionInfoDialog = new Dialog(getActivity());
                            //应用上架要求添加权限使用说明
                            String permissionInfoTitle = "";
                            String permissionInfoContent = "";
                            permissionInfoTitle = getResources().getString(R.string.permission_info_title_camera);
                            permissionInfoContent = getResources().getString(R.string.permission_info_content_camera);
                            if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(permissionInfoContent)) {
                                CustomPermissionUtil.showPermissionInfo(getActivity()
                                        , permissionInfoDialog, permissionInfoTitle, permissionInfoContent);
                            }
                            AppPermissionUtil.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, new AppPermissionUtil.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    if (!checkHasStoragePermission()) {
                                        return;
                                    }
                                    Intent intent = new Intent(getActivity(), ScanActivity.class);
                                    startActivity(intent);
                                    permissionInfoDialog.dismiss();
                                }

                                @Override
                                public void onPermissionDenied() {
                                    permissionInfoDialog.dismiss();
                                }
                            });
                        }
                    })
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 用户拒绝权限申请
                        }
                    })
                    .show();
        } else {
            // 已获得权限，执行相关操作
            if (!checkHasStoragePermission()) {
                return;
            }
            startActivityForResult(new Intent(getActivity(), ScanActivity.class), 100);
        }

    }

    public static final int REQUEST_CODE_ASK_PERMISSIONS = 200;

    private boolean checkHasStoragePermission() {
        // 从6.0系统(API 23)开始，访问外置存储需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = getActivity().checkSelfPermission(Manifest.permission.CAMERA);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                        new String[]{Manifest.permission.CAMERA},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RongUserInfoManager.getInstance().removeUserDataObserver(mUserDataObserver);
    }

    private RongUserInfoManager.UserDataObserver mUserDataObserver =
            new RongUserInfoManager.UserDataObserver() {
                @Override
                public void onUserUpdate(io.rong.imlib.model.UserInfo userInfo) {
                    if (userInfo != null
                            && getActivity() != null
                            && userInfo.getUserId()
                            .equals(RongIMClient.getInstance().getCurrentUserId())) {
                        ThreadManager.getInstance()
                                .runOnUIThread(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                if (getActivity() == null) {
                                                    return;
                                                }
                                                Glide.with(getActivity())
                                                        .load(userInfo.getPortraitUri())
                                                        .placeholder(R.drawable.rc_default_portrait)
                                                        .into(uivUserInfo.getHeaderImageView());
                                                uivUserInfo.setName(userInfo.getName());
                                            }
                                        });
                    }
                }

                @Override
                public void onGroupUpdate(Group group) {
                }

                @Override
                public void onGroupUserInfoUpdate(GroupUserInfo groupUserInfo) {
                }
            };

    /**
     * 保存并同步用户的昵称和头像
     *
     * @param userId
     * @param nickName
     * @param portraitUrl
     */

    public void saveAndSyncUserInfo(String userId, String nickName, String portraitUrl) {
        UserDao userDao = DBManager.getInstance(getContext()).getUserDao();
        if (userDao != null) {
            UserInfo userInfo = userDao.getUserByIdSync(userId);
            if (nickName == null) {
                nickName = userInfo == null ? "" : userInfo.getName();
            }

            if (portraitUrl == null) {
                portraitUrl = userInfo == null ? "" : userInfo.getPortraitUri();
            }

            int i =
                    userDao.updateNameAndPortrait(
                            userId,
                            nickName,
                            CharacterParser.getInstance().getSpelling(nickName),
                            portraitUrl);
            SLog.d("ss_update", "i=" + i);

            IMManager.getInstance()
                    .updateUserInfoCache(
                            userId,
                            nickName,
                            Uri.parse(portraitUrl),
                            userInfo == null ? "" : userInfo.getAlias());
        }
    }
}
